// pages/goods_list/index.js
import {request}  from '../../request/index.js'

Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabs: [
            {id: 1, label: '综合', isActive: true},
            {id: 2, label: '销量', isActive: false},
            {id: 3, label: '价格', isActive: false},
        ],
        goodsList: []

    },
    QueryParams: {
        query: '',
        cid: '',
        pagenum: 1,
        pagesize: 10
    },
    totalPage: 0,

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.QueryParams.cid = options.cid;
        this.getGoodList()
    },
    getGoodList() {       
        // 请求
        request({
            url: '/goods/search',
            ...this.QueryParams,
        }).then(res => {
            const {goods, total} = res.message;
            // 计算总页码
            this.totalPage = Math.ceil(total / this.QueryParams.pagesize)

            this.setData({
                goodsList: [...this.data.goodsList, ...goods],
            })

            // 手动关闭下拉刷新的loading状态
            wx.stopPullDownRefresh()            
        })
    },
    // tabs的事件处理函数
    handleChangeTab(e) {
        const {index} = e.detail;
        const {tabs} = this.data;
        tabs.forEach((item, i)=>item.isActive=(i===index))
        this.setData({
            tabs
        })

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        this.setData({
            goodsList: []
        })
        this.QueryParams.pagenum = 1;
        this.QueryParams.query = '';
        this.getGoodList()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        /**
         * 先判断是否有下一页， 必须先有总页数
         * 1.有， 页码++，请求
         * 2.无， 提示信息
         */
        if(this.QueryParams.pagenum >= this.totalPage) {
            // 无下一页
            wx.showToast({
              title: '暂无下一页',
            })
        }else {
            this.QueryParams.pagenum++;
            this.getGoodList()
        }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})